/**
 * This class helps to write Logs in the text files
 */

package com.comp6231.replica2.server.helper;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 
 * @author Farzana Alam
 * 
 */
public class Utility {

	/**
	 * 
	 * @param log
	 * @param fileName
	 * @return @
	 */
	private static Object lock = new Object();

	public static boolean writeLog(Log log, String fileName) {
		synchronized (lock) {
			/*
			 * This method formats the Log objects and write them in the text
			 * file
			 */
			try {
				File file = new File(System.getProperty("user.dir")
						+ "/src/com/comp6231/replica2/logs/" + fileName);
				FileWriter fileWriter;
				BufferedWriter bufferedWriter;

				// This block prints the header row when the file is first
				// created
				if (!file.exists()) {
					fileWriter = new FileWriter(file, true);
					bufferedWriter = new BufferedWriter(fileWriter);
					bufferedWriter.write("Badge ID \tLocation ID\t\tOPeration "
							+ "Description\t\t\tTime & Date\t\t\t"
							+ "Operation Status\t Record ID\tRecord Status\n");
					bufferedWriter
							.write("---------\t\t-----------\t\t-------------"
									+ "--------\t\t\t-----------\t\t\t----------------"
									+ "\t ---------\t-------------\n");

				} else {
					fileWriter = new FileWriter(file, true);
					bufferedWriter = new BufferedWriter(fileWriter);
				}

				bufferedWriter.write(log.badgeID + "\t\t" + log.locationID
						+ "\t\t " + log.operationDescription + "\t"
						+ log.timeStamp + "\t\t" + log.operationStatus
						+ "\t\t" + log.recordID +"\t\t" + log.recordStatus);
				bufferedWriter.write("\n");

				bufferedWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}
	// public static void main(String[] args) {
	// Utility.writeLog(new Log("SPB", "Missing record created for LName-63",
	// "2013/10/01 00:12:28", "Successful", "MR00001", "MISSING"),
	// "d:\\test.txt");
	// }
}
